package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.ILegalCaseService;
import com.mdd.admin.validate.LegalCaseCreateValidate;
import com.mdd.admin.validate.LegalCaseSearchValidate;
import com.mdd.admin.validate.LegalCaseUpdateValidate;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.vo.LegalCaseDetailVo;
import com.mdd.admin.vo.LegalCaseListedExcelVo;
import com.mdd.admin.vo.LegalCaseListedVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.LegalCase;
import com.mdd.common.enums.CaseStatusEnum;
import com.mdd.common.mapper.LegalCaseMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 案件实现类
 * @author LikeAdmin
 */
@Service
public class LegalCaseServiceImpl implements ILegalCaseService {
        
    @Resource
    LegalCaseMapper legalCaseMapper;

    /**
     * 案件列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<LegalCaseListedVo>
     */
    @Override
    public PageResult<LegalCaseListedVo> list(PageValidate pageValidate, LegalCaseSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        MPJQueryWrapper<LegalCase> mpjQueryWrapper = new MPJQueryWrapper<>();
        mpjQueryWrapper.selectAll(LegalCase.class)
                .select("t2.area_name as areaName, t3.real_name as userName, t3.mobile as userMobile, t4.real_name as adminName, t5.real_name as caseCooperationUserName")
                .leftJoin("legal_area_city t2 on t2.area_id = t.area_id")
                .leftJoin("la_user t3 on t3.id = t.user_id")
                .leftJoin("la_user t4 on t4.id = t.admin_id")
                .leftJoin("la_user t5 on t5.id = t.case_cooperation_user_id")
                .eq("t.delete_time", 0)
                .orderByDesc("t.id");

        legalCaseMapper.setSearch(mpjQueryWrapper, searchValidate, new String[]{
                "like:caseName@t.case_name:str",
                "=:status@t.status:str",
                "=:caseType@t.case_type:str",
                "=:jumpContractSign@t.jump_contract_sign:str",
        });

        if (StringUtils.isNotEmpty(searchValidate.getStatusArr())) {
            String[] split = searchValidate.getStatusArr().split(",");
            mpjQueryWrapper.in("status", split);
        }

        IPage<LegalCaseListedVo> iPage = legalCaseMapper.selectJoinPage(
                new Page<>(page, limit), LegalCaseListedVo.class, mpjQueryWrapper);
        for (LegalCaseListedVo vo : iPage.getRecords()) {
            if (vo.getAdminType() == 1) {
                vo.setAdminName("【后台审核】");
            } else if (vo.getAdminType() == 2) {
                String adminName = vo.getAdminName();
                vo.setAdminName(adminName+"【APP端审核】");
            }
            if (StringUtils.isNotEmpty(vo.getCreateTime())) {
                String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(vo.getCreateTime()) * 1000));
                vo.setCreateTimeStr(format);
            }
        }
        return PageResult.iPageHandle(iPage);
    }

    @Override
    public List<LegalCaseListedExcelVo> list(LegalCaseSearchValidate searchValidate) {
        MPJQueryWrapper<LegalCase> mpjQueryWrapper = new MPJQueryWrapper<>();
        mpjQueryWrapper.selectAll(LegalCase.class)
                .select("t2.area_name as areaName, t3.real_name as userName, t3.mobile as userMobile, t4.real_name as adminName, t5.real_name as caseCooperationUserName")
                .leftJoin("legal_area_city t2 on t2.area_id = t.area_id")
                .leftJoin("la_user t3 on t3.id = t.user_id")
                .leftJoin("la_user t4 on t4.id = t.admin_id")
                .leftJoin("la_user t5 on t5.id = t.case_cooperation_user_id")
                .eq("t.delete_time", 0)
                .eq("t.case_type", 1)
                .orderByDesc("t.id");

        legalCaseMapper.setSearch(mpjQueryWrapper, searchValidate, new String[]{
                "like:caseName@t.case_name:str",
                "=:status@t.status:str",
        });

        if (StringUtils.isNotEmpty(searchValidate.getStatusArr())) {
            String[] split = searchValidate.getStatusArr().split(",");
            mpjQueryWrapper.in("status", split);
        }
        List<LegalCaseListedExcelVo> legalCaseListedVos = legalCaseMapper.selectJoinList(LegalCaseListedExcelVo.class, mpjQueryWrapper);
        for (LegalCaseListedExcelVo vo : legalCaseListedVos) {
            if (vo.getAdminType() == 1) {
                vo.setAdminName("【后台审核】");
            } else if (vo.getAdminType() == 2) {
                String adminName = vo.getAdminName();
                vo.setAdminName(adminName+"【APP端审核】");
            }
            if (StringUtils.isNotEmpty(vo.getCreateTime())) {
                String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date(Long.parseLong(vo.getCreateTime()) * 1000));
                vo.setCreateTimeStr(format);
            }
            if (vo.getStatus() != null ) {
                vo.setStatusStr(CaseStatusEnum.getMsgByCode(vo.getStatus()));
            }
        }
        return legalCaseListedVos;
    }

    /**
     * 案件详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return LegalCase
     */
    @Override
    public LegalCaseDetailVo detail(Integer id) {
        LegalCase model = legalCaseMapper.selectOne(
                new QueryWrapper<LegalCase>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        LegalCaseDetailVo vo = new LegalCaseDetailVo();
        BeanUtils.copyProperties(model, vo);
        vo.setEndTime(TimeUtils.timestampToDate(model.getEndTime()));
        return vo;
    }

    /**
     * 案件新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(LegalCaseCreateValidate createValidate) {
        LegalCase model = new LegalCase();
        model.setAId(createValidate.getAId());
        model.setCaseType(createValidate.getCaseType());
        model.setUserId(createValidate.getUserId());
        model.setCaseTradeNo(createValidate.getCaseTradeNo());
        model.setCaseName(createValidate.getCaseName());
        model.setType(createValidate.getType());
        model.setAreaId(createValidate.getAreaId());
        model.setAreaName(createValidate.getAreaName());
        model.setZqType(createValidate.getZqType());
        model.setZwType(createValidate.getZwType());
        model.setZqName(createValidate.getZqName());
        model.setZqIdCard(createValidate.getZqIdCard());
        model.setZqIdCardImage(createValidate.getZqIdCardImage());
        model.setZqMobile(createValidate.getZqMobile());
        model.setZqAddress(createValidate.getZqAddress());
        model.setZwName(createValidate.getZwName());
        model.setZwIdCard(createValidate.getZwIdCard());
        model.setZwIdCardImage(createValidate.getZwIdCardImage());
        model.setZwMobile(createValidate.getZwMobile());
        model.setZwAddress(createValidate.getZwAddress());
        model.setZwCompanyAddress(createValidate.getZwCompanyAddress());
        model.setZqCName(createValidate.getZqCName());
        model.setZqCMobile(createValidate.getZqCMobile());
        model.setZqCAddress(createValidate.getZqCAddress());
        model.setZqCLicense(createValidate.getZqCLicense());
        model.setZqCLegalName(createValidate.getZqCLegalName());
        model.setZqCLegalIdCard(createValidate.getZqCLegalIdCard());
        model.setZqCLegalMobile(createValidate.getZqCLegalMobile());
        model.setZqCLegalIdCardImage(createValidate.getZqCLegalIdCardImage());
        model.setZwCName(createValidate.getZwCName());
        model.setZwCMobile(createValidate.getZwCMobile());
        model.setZwCAddress(createValidate.getZwCAddress());
        model.setZwCLicense(createValidate.getZwCLicense());
        model.setZwCLegalName(createValidate.getZwCLegalName());
        model.setZwCLegalIdCard(createValidate.getZwCLegalIdCard());
        model.setZwCLegalMobile(createValidate.getZwCLegalMobile());
        model.setZwCLegalIdCardImage(createValidate.getZwCLegalIdCardImage());
        model.setMoney(createValidate.getMoney());
        model.setJdDate(createValidate.getJdDate());
        model.setZqMoney(createValidate.getZqMoney());
        model.setNowRates(createValidate.getNowRates());
        model.setMoneyDate(createValidate.getMoneyDate());
        model.setMoneyDateTotal(createValidate.getMoneyDateTotal());
        model.setEvidenceImage(createValidate.getEvidenceImage());
        model.setEvidenceVoice(createValidate.getEvidenceVoice());
        model.setEvidenceVideo(createValidate.getEvidenceVideo());
        model.setInfo(createValidate.getInfo());
        model.setYgPriceLow(createValidate.getYgPriceLow());
        model.setYgPriceHigh(createValidate.getYgPriceHigh());
        model.setPrice(createValidate.getPrice());
        model.setCaseScale(createValidate.getCaseScale());
        model.setPartnerScale(createValidate.getPartnerScale());
        model.setLawyerScale(createValidate.getLawyerScale());
        model.setRecommendScale(createValidate.getRecommendScale());
        model.setIsLinkUser(createValidate.getIsLinkUser());
        model.setStatus(createValidate.getStatus());
        model.setRejectReason(createValidate.getRejectReason());
        model.setAdminType(createValidate.getAdminType());
        model.setAdminId(createValidate.getAdminId());
        model.setPartnerId(createValidate.getPartnerId());
        model.setExamineTime(createValidate.getExamineTime());
        model.setLawyerId(createValidate.getLawyerId());
        model.setTakeTime(createValidate.getTakeTime());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setEndTime(System.currentTimeMillis() / 1000);
        model.setIsFy(createValidate.getIsFy());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setAgreeImg(createValidate.getAgreeImg());
        model.setAgreeRemark(createValidate.getAgreeRemark());
        model.setJumpContractSign(createValidate.getJumpContractSign());
        model.setOfflineSignFiles(createValidate.getOfflineSignFiles());
        model.setIsShow(createValidate.getIsShow());
        model.setCaseCooperationUserId(createValidate.getCaseCooperationUserId());
        model.setChangeLawCanTakeCase(createValidate.getChangeLawCanTakeCase());
        model.setIsAdminUpload(createValidate.getIsAdminUpload());
        model.setAdminUploader(createValidate.getAdminUploader());
        legalCaseMapper.insert(model);
    }

    /**
     * 案件编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(LegalCaseUpdateValidate updateValidate) {
        LegalCase model = legalCaseMapper.selectOne(
                new QueryWrapper<LegalCase>()
                    .eq("id",  updateValidate.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(updateValidate.getId());
        model.setAId(updateValidate.getAId());
        model.setCaseType(updateValidate.getCaseType());
        model.setUserId(updateValidate.getUserId());
        model.setCaseTradeNo(updateValidate.getCaseTradeNo());
        model.setCaseName(updateValidate.getCaseName());
        model.setType(updateValidate.getType());
        model.setAreaId(updateValidate.getAreaId());
        model.setAreaName(updateValidate.getAreaName());
        model.setZqType(updateValidate.getZqType());
        model.setZwType(updateValidate.getZwType());
        model.setZqName(updateValidate.getZqName());
        model.setZqIdCard(updateValidate.getZqIdCard());
        model.setZqIdCardImage(updateValidate.getZqIdCardImage());
        model.setZqMobile(updateValidate.getZqMobile());
        model.setZqAddress(updateValidate.getZqAddress());
        model.setZwName(updateValidate.getZwName());
        model.setZwIdCard(updateValidate.getZwIdCard());
        model.setZwIdCardImage(updateValidate.getZwIdCardImage());
        model.setZwMobile(updateValidate.getZwMobile());
        model.setZwAddress(updateValidate.getZwAddress());
        model.setZwCompanyAddress(updateValidate.getZwCompanyAddress());
        model.setZqCName(updateValidate.getZqCName());
        model.setZqCMobile(updateValidate.getZqCMobile());
        model.setZqCAddress(updateValidate.getZqCAddress());
        model.setZqCLicense(updateValidate.getZqCLicense());
        model.setZqCLegalName(updateValidate.getZqCLegalName());
        model.setZqCLegalIdCard(updateValidate.getZqCLegalIdCard());
        model.setZqCLegalMobile(updateValidate.getZqCLegalMobile());
        model.setZqCLegalIdCardImage(updateValidate.getZqCLegalIdCardImage());
        model.setZwCName(updateValidate.getZwCName());
        model.setZwCMobile(updateValidate.getZwCMobile());
        model.setZwCAddress(updateValidate.getZwCAddress());
        model.setZwCLicense(updateValidate.getZwCLicense());
        model.setZwCLegalName(updateValidate.getZwCLegalName());
        model.setZwCLegalIdCard(updateValidate.getZwCLegalIdCard());
        model.setZwCLegalMobile(updateValidate.getZwCLegalMobile());
        model.setZwCLegalIdCardImage(updateValidate.getZwCLegalIdCardImage());
        model.setMoney(updateValidate.getMoney());
        model.setJdDate(updateValidate.getJdDate());
        model.setZqMoney(updateValidate.getZqMoney());
        model.setNowRates(updateValidate.getNowRates());
        model.setMoneyDate(updateValidate.getMoneyDate());
        model.setMoneyDateTotal(updateValidate.getMoneyDateTotal());
        model.setEvidenceImage(updateValidate.getEvidenceImage());
        model.setEvidenceVoice(updateValidate.getEvidenceVoice());
        model.setEvidenceVideo(updateValidate.getEvidenceVideo());
        model.setInfo(updateValidate.getInfo());
        model.setYgPriceLow(updateValidate.getYgPriceLow());
        model.setYgPriceHigh(updateValidate.getYgPriceHigh());
        model.setPrice(updateValidate.getPrice());
        model.setCaseScale(updateValidate.getCaseScale());
        model.setPartnerScale(updateValidate.getPartnerScale());
        model.setLawyerScale(updateValidate.getLawyerScale());
        model.setRecommendScale(updateValidate.getRecommendScale());
        model.setIsLinkUser(updateValidate.getIsLinkUser());
        model.setStatus(updateValidate.getStatus());
        model.setRejectReason(updateValidate.getRejectReason());
        model.setAdminType(updateValidate.getAdminType());
        model.setAdminId(updateValidate.getAdminId());
        model.setPartnerId(updateValidate.getPartnerId());
        model.setExamineTime(updateValidate.getExamineTime());
        model.setLawyerId(updateValidate.getLawyerId());
        model.setTakeTime(updateValidate.getTakeTime());
        model.setIsFy(updateValidate.getIsFy());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        model.setAgreeImg(updateValidate.getAgreeImg());
        model.setAgreeRemark(updateValidate.getAgreeRemark());
        model.setJumpContractSign(updateValidate.getJumpContractSign());
        model.setOfflineSignFiles(updateValidate.getOfflineSignFiles());
        model.setIsShow(updateValidate.getIsShow());
        model.setCaseCooperationUserId(updateValidate.getCaseCooperationUserId());
        model.setChangeLawCanTakeCase(updateValidate.getChangeLawCanTakeCase());
        model.setIsAdminUpload(updateValidate.getIsAdminUpload());
        model.setAdminUploader(updateValidate.getAdminUploader());
        legalCaseMapper.updateById(model);
    }

    /**
     * 案件删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        LegalCase model = legalCaseMapper.selectOne(
                new QueryWrapper<LegalCase>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        legalCaseMapper.delete(new QueryWrapper<LegalCase>().eq("id", id));
    }

    @Override
    public void isShow(Integer id, Integer adminId) {
        LegalCase model = legalCaseMapper.selectOne(
                new QueryWrapper<LegalCase>()
                        .eq("id", id)
                        .last("limit 1"));
        Assert.notNull(model, "数据不存在!");

        Integer isShow = model.getIsShow() == 1 ? 0 : 1;
        model.setIsShow(isShow);
        legalCaseMapper.updateById(model);
    }

    @Override
    public void canTake(Integer id, Integer adminId) {
        LegalCase model = legalCaseMapper.selectOne(
                new QueryWrapper<LegalCase>()
                        .eq("id", id)
                        .last("limit 1"));
        Assert.notNull(model, "数据不存在!");

        Integer canTake = model.getChangeLawCanTakeCase() == 1 ? 0 : 1;
        model.setChangeLawCanTakeCase(canTake);
        legalCaseMapper.updateById(model);
    }

}
